<?php

namespace common\models;

use Firebase\JWT\JWT;
use Yii;
use yii\base\Exception;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\BadRequestHttpException;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "member".
 *
 * @property int    $member_id
 * @property int    $member_status               状态
 * @property string $member_email                用户邮箱
 * @property string $member_phone                用户手机
 * @property int    $member_created_at
 * @property int    $member_updated_at
 * @property string $member_auth_key
 * @property string $member_password_hash        密码
 * @property string $member_password_reset_token 充值密码token
 */
class Member extends ActiveRecord implements IdentityInterface
{
    const STATUS_ACTIVE = 10;//激活用户
    const STATUS_CLOSE  = 0;//关闭用户
    //用户注册密码
    public $member_password;
    //cookie加密串
    const SALT = "zc_key";
    //session下标
    const SESSION_KEY = '_memberid';

    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'member';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['member_email', 'member_phone', 'member_password'], 'required'],
            [['member_status', 'member_created_at', 'member_updated_at'], 'integer'],
            [['member_email'], 'string', 'max' => 45],
            [['member_password'], 'string', 'min' => 6, 'max' => 15],
            [['member_auth_key'], 'string', 'max' => 32],
            [['member_password_hash'], 'string', 'max' => 255],
            [['member_password_reset_token'], 'string', 'max' => 120],
            [['member_phone'], 'unique'],
            [['member_email'], 'unique'],
            ['member_email', 'email'],
            [
                'member_phone',
                'match',
                'pattern' => '/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/',
                'message' => '手机号不正确',
            ],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'member_id'                   => 'Member ID',
            'member_status'               => '状态',
            'member_email'                => '用户邮箱',
            'member_phone'                => '用户手机',
            'member_created_at'           => 'Member Created At',
            'member_updated_at'           => 'Member Updated At',
            'member_auth_key'             => 'Member Auth Key',
            'member_password_hash'        => '密码',
            'member_password_reset_token' => '充值密码token',
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            [
                'class'              => TimestampBehavior::className(),
                'createdAtAttribute' => 'member_created_at',
                'updatedAtAttribute' => 'member_updated_at',
            ],
        ];
    }

    /**
     * Finds an identity by the given ID.
     *
     * @param string|int $id the ID to be looked for
     *
     * @return IdentityInterface the identity object that matches the given ID.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentity($id)
    {
        $identity = static::findOne($id);
        if ($identity->member_status == self::STATUS_ACTIVE) {
            return $identity;
        }

        return null;
    }

    /**
     * Finds an identity by the given token.
     *
     * @param mixed $token the token to be looked for
     * @param mixed $type  the type of the token. The value of this parameter depends on the implementation.
     *                     For example, [[\yii\filters\auth\HttpBearerAuth]] will set this parameter to be
     *                     `yii\filters\auth\HttpBearerAuth`.
     *
     * @return IdentityInterface the identity object that matches the given token.
     * Null should be returned if such an identity cannot be found
     * or the identity is not in an active state (disabled, deleted, etc.)
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        try {
            $decoded = JWT::decode($token, self::SALT, ['HS256']);

            $mid = $decoded->mid;
            $exp = $decoded->exp;
            if (time() > $exp) {
                throw new BadRequestHttpException('token 已经过期,请重新登录');
            }

            return static::findOne(['member_id' => $mid, 'member_status' => self::STATUS_ACTIVE]);
        } catch (\Exception $e) {
            return null;
        }
    }
    /**
     * Returns an ID that can uniquely identify a user identity.
     *
     * @return string|int an ID that uniquely identifies a user identity.
     */
    public function getId()
    {
        return $this->member_id;
    }

    /**
     * Returns a key that can be used to check the validity of a given identity ID.
     *
     * The key should be unique for each individual user, and should be persistent
     * so that it can be used to check the validity of the user identity.
     *
     * The space of such keys should be big enough to defeat potential identity attacks.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     *
     * @return string a key that is used to check the validity of a given identity ID.
     * @see validateAuthKey()
     * @throws \yii\base\Exception
     */
    public function getAuthKey()
    {
        throw new Exception('该方法未被使用');
    }

    /**
     * Validates the given auth key.
     *
     * This is required if [[User::enableAutoLogin]] is enabled.
     *
     * @param string $authKey the given auth key
     *
     * @return bool whether the given auth key is valid.
     * @see getAuthKey()
     * @throws \yii\base\Exception
     */
    public function validateAuthKey($authKey)
    {
        throw new Exception('该方法未被使用');
    }

    /**
     * 用户注册
     *
     * @return bool
     * @throws \yii\base\Exception
     */
    public function signUp()
    {
        if (!$this->validate()) {
            throw new BadRequestHttpException(current($this->getFirstErrors()));
        }

        $this->member_password_hash = Yii::$app->security->generatePasswordHash($this->member_password);
        $this->member_auth_key      = Yii::$app->security->generateRandomString();
        $this->member_status        = self::STATUS_ACTIVE;

        return $this->save(false) ? true : false;
    }

    /**
     * @param      $phone
     * @param      $password
     *
     * @param bool $rememberMe
     *
     * @return array
     * @throws \yii\web\BadRequestHttpException
     */
    public static function login($phone, $password)
    {
        /** @var $member \common\models\Member */
        $member = static::find()
            ->where([
                'or',
                ['member_phone' => $phone],
                ['member_email' => $phone],
            ])
            ->andWhere(['member_status' => self::STATUS_ACTIVE])
            ->one();
        if ($member === null || !\Yii::$app->security->validatePassword($password, $member->member_password_hash)) {
            throw new BadRequestHttpException('用户名或密码错误');
        }
        if (Yii::$app->user->login($member)) {
            $token = JWT::encode([
                'mid' => \Yii::$app->user->identity->member_id,
                'exp' => static::expireTime(),
            ], self::SALT);

            return [
                'token' => $token,
            ];
        } else {
            throw new BadRequestHttpException('登录失败!');
        }
    }

    /**
     * 过期时间,默认 1 周
     *
     * @return int
     */
    public static function expireTime()
    {
        return time() + 7 * 24 * 60 * 60;
    }
}
